package com.hy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hy.Result.ResponseResult;

import com.hy.file.service.impl.FileStorageServiceImpl;
import com.hy.mapper.VaccinationAppointmentMapper;
import com.hy.pojeVo.QueryParam;
import com.hy.pojeVo.VaccinationAppointmentVO;
import com.hy.pojo.vaccine.VaccinationAppointment;
import com.hy.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class VaccinationAppointmentServiceImpl extends ServiceImpl<VaccinationAppointmentMapper, VaccinationAppointment>
        implements VaccinationAppointmentService {

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    private VaccinationAppointmentMapper vaccinationAppointmentMapper;
    @Autowired
    private FileStorageServiceImpl fileStorageService;
    @Override
    public ResponseResult createAppointment(VaccinationAppointment appointment) {
        //参数校验
        if (appointment.getUserId() == null || appointment.getVaccineId() == null
                || appointment.getAppointmentDate() == null || appointment.getAppointmentTime() == null) {
            return new ResponseResult(400, "参数错误：缺少必要参数", null);
        }

        //同一个人同一天不能预约同一个疫苗
        LambdaQueryWrapper<VaccinationAppointment> l = new LambdaQueryWrapper<>();
        l.eq(VaccinationAppointment::getUserId, appointment.getUserId());
        l.eq(VaccinationAppointment::getAppointmentDate, appointment.getAppointmentDate());
        l.eq(VaccinationAppointment::getVaccineId, appointment.getVaccineId());
//        l.eq(VaccinationAppointment::getIsDeleted, 0); // 只检查未删除的记录

        VaccinationAppointment vaccinationAppointment = vaccinationAppointmentMapper.selectOne(l);
        if (vaccinationAppointment != null){
            return new ResponseResult(400, "同一个人同一天不能预约同一个疫苗", null);
        }

        // 生成预约编号
        appointment.setAppointmentNo(String.valueOf(snowflakeIdWorker.nextId()));
        appointment.setStatus(0); // 设置初始状态为待确认
//        appointment.setIsDeleted(0); // 确保设置为未删除
        //创建人
        appointment.setCreateBy(appointment.getUserId());
        //更新时间
        appointment.setCreateTime(new Date());
        boolean save = save(appointment);
        if (save) {
            return new ResponseResult(200, "预约创建成功", appointment);
        }

        return new ResponseResult(400, "预约创建失败", null);
    }

    @Override
    public ResponseResult updateAppointment(VaccinationAppointment appointment) {
        try {
            boolean success = updateById(appointment);
            if (success) {
                return new ResponseResult(200, "预约更新成功", appointment);
            }
            return new ResponseResult(400, "预约更新失败", null);
        } catch (Exception e) {
            return new ResponseResult(500, "系统错误：" + e.getMessage(), null);
        }
    }

    @Override
    public ResponseResult deleteAppointment(Integer id) {
        try {
            // 查询预约是否存在
            VaccinationAppointment appointment = getById(id);
            if (appointment == null) {
                return new ResponseResult(400, "预约不存在", null);
            }

            // 检查预约状态是否允许删除（只允许待确认状态的预约可以删除）
            if (appointment.getStatus() != 0) {
                return new ResponseResult(400, "只有待确认状态的预约可以删除", null);
            }

            // 执行物理删除
            boolean success = removeById(id);
            if (success) {
                return new ResponseResult(200, "预约删除成功", null);
            }
            return new ResponseResult(400, "预约删除失败", null);
        } catch (Exception e) {
            return new ResponseResult(500, "系统错误：" + e.getMessage(), null);
        }
    }

    @Override
    public ResponseResult searchByKeyword(QueryParam queryParam) {
        try {
            PageHelper.startPage(queryParam.getPageNum(), queryParam.getPageSize());
            List<VaccinationAppointment> appointments = baseMapper.searchAppointments(queryParam.getKeyword());
            PageInfo<VaccinationAppointment> pageInfo = new PageInfo<>(appointments);
            return new ResponseResult(200, "查询成功", pageInfo);
        } catch (Exception e) {
            return new ResponseResult(500, "查询失败：" + e.getMessage(), null);
        }
    }

    @Override
    public ResponseResult getAppointmentsByUserId(Long userId) {
        try {
            LambdaQueryWrapper<VaccinationAppointment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VaccinationAppointment::getUserId, userId)
                    .orderByDesc(VaccinationAppointment::getCreateTime);

            List<VaccinationAppointment> appointments = this.list(queryWrapper);
            return ResponseResult.okResult(appointments);
        } catch (Exception e) {
            return ResponseResult.errorResult(500, "查询预约信息失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult getAppointmentDetailsByUserId(Long userId) {
        try {
            if (userId == null) {
                return ResponseResult.errorResult(400, "用户ID不能为空");
            }

            List<VaccinationAppointmentVO> appointments = baseMapper.getAppointmentDetailsByUserId(userId);
            return ResponseResult.okResult(appointments);
        } catch (Exception e) {
            return ResponseResult.errorResult(500, "查询预约详细信息失败：" + e.getMessage());
        }
    }
} 